package leetcode.code1521;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	int[] and;
	int[] arr;

	public int closestToTarget(int[] arr, int target) {
		this.arr = arr;
		int n = arr.length;
		and = new int[n << 2];
		build(1, 1, n);
		int min = arr[0];
		for (int i = 1; i < arr.length; i++) {
			min &= arr[i];
		}
		int ans = Math.abs(target - min);
		for (int i = 1; i < and.length; i++) {
			int cur = and[i];
			if (cur > 0 && Math.abs(cur - target) < ans) {
				ans = Math.abs(cur - target);
			}
		}
		return ans;
	}

	private void build(int o, int l, int r) {
		if (l == r) {
			and[o] = this.arr[l - 1];
			return;
		}
		int m = ((r - l) >> 1) + l;
		build(o << 1, l, m);
		build(o << 1 | 1, m + 1, r);
		and[o] = and[o << 1] & and[o << 1 | 1];
	}

	@Override
	public void debug4() {
		H.compare(4, this.closestToTarget(H.str2array3("[70,15,21,96]"), 4));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
